require.config({
    paths: {
      'diff': '../addons/knowbase/js/diff',
      'diff2html': '../addons/knowbase/js/diff2html',
      'diff2htmlui': '../addons/knowbase/js/diff2html-ui',
    },
    shim: {
      'diff2html': {
        deps: [
          'css!../addons/knowbase/css/diff2html.min.css',
          'css!../addons/knowbase/css/styles_github.min.css',
        ],
        exports: 'Diff2Html'
      }
    }
  });
define(['jquery', 'bootstrap', 'backend', 'table', 'form','diff','diff2html','diff2htmlui'], function ($, undefined, Backend, Table, Form,Diff,Diff2Html,Diff2HtmlUI) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'knowbase/project_page_history/index' + location.search,
                    add_url: 'knowbase/project_page_history/add',
                    edit_url: 'knowbase/project_page_history/edit',
                    del_url: 'knowbase/project_page_history/del',
                    multi_url: 'knowbase/project_page_history/multi',
                    import_url: 'knowbase/project_page_history/import',
                    table: 'knowbase_project_page_history',
                }
            });

            var table = $("#table");

            var buttons = [{
                name: 'edit',
                icon: 'fa fa-pencil',
                title: __('Edit'),
                extend: 'data-toggle="tooltip" data-container="body" data-area=["100%","100%"]',
                classname: 'btn btn-xs btn-success btn-editone'
            }, {
                name: 'del',
                icon: 'fa fa-trash',
                title: __('Del'),
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-danger btn-delone',
                hidden:function (row){
                   return false;
                }
            }];

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),operate:false},
                        {field: 'knowbase_project_id', title: __('Knowbase_project_id'), searchList: function(column){
                            return '<input id="c-knowbase_project_id"  data-source="knowbase/project/index" ' +
                              'data-order-by="id" data-multiple="false" ' +
                              'data-page-size="20"  '+
                              'data-search-field="title" '+
                              'data-field="title" ' +
                              'data-pagination="true" '+
                              'class="form-control selectpage" ' +
                              'name="knowbase_project_id" type="text" value="">';
                        },formatter:function (value,row,index){
                            return row.project?row.project.title:"--";
                        }},
                        {field: 'knowbase_project_page_id', title: __('Knowbase_project_page_id') ,searchList: function(column){
                            return '<input id="c-knowbase_project_page_id"  data-source="knowbase/project_page/getList" ' +
                              'data-order-by="id" data-multiple="false" ' +
                              'data-page-size="20"  '+
                              'data-search-field="title" '+
                              'data-field="title" ' +
                              'data-pagination="true" '+
                              'class="form-control selectpage" ' +
                              'name="knowbase_project_page_id" type="text" value="">';
                        },formatter:function (value,row,index){
                            return row.project_page?row.project_page.title:"--";
                        }},
                        {field: 'remarks', title: __('Remarks'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'admin_id', title: __('Admin_id'),searchList: function(column){
                            return '<input id="c-admin_id"  data-source="auth/admin/index" ' +
                              'data-order-by="id" data-multiple="false" ' +
                              'data-page-size="20"  '+
                              'data-search-field="username" '+
                              'data-field="username" ' +
                              'data-pagination="true" '+
                              'class="form-control selectpage" ' +
                              'name="admin_id" type="text" value="">';
                        },formatter:function (value,row,index){
                            return row.admin?row.admin.username:"--";
                        }},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,buttons:buttons}
                    ]
                ]
            });

            $('.btn-remove').click(function (e) {
                e.preventDefault();
                Layer.prompt({title: __('tips_remove_before_days'), formType: 0,value:7}, function (value, index) {
                    Fast.api.ajax({
                        url: 'knowbase/project_page_history/remove',
                        type: 'post',
                        data: {'day':value}
                    }, function (data, ret) {
                        Layer.close(index);
                        $(".btn-refresh").trigger("click");
                    });
                });

            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        page_history: function () {
            var from = Fast.api.query('from');
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    history_url: 'knowbase/project_page_history/index' + location.search,
                    edit_url: 'knowbase/project_page_history/edit',
                    del_url: from =='project_page'?false:'knowbase/project_page_history/del',
                    table: 'knowbase_project_page_history',
                }
            });
            
            var table = $("#table");
            
            var buttons = [ 
              {
                name: 'compare',
                icon: 'fa fa-calculator',
                title: '与最新版本对比',
                extend: 'data-toggle="tooltip" data-container="body" data-area=["100%","100%"]',
                classname: 'btn btn-xs btn-primary btn-compareone',
                // url: function (row){
                //       return 'knowbase/project_page_history/edit?ids='+row.id+'&from=project_page';
                // }
            }, {
                name: 'reduction',
                icon: 'fa fa-window-restore',
                title: '还原该版本',
                confirm:'确定还原该版本吗？',
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-warning btn-ajax btn-reduction',
                url: 'knowbase/project_page_history/reduction',
                success:function (data){
                    setTimeout(function (){
                        parent.window.location.reload();
                    },1000);
                }
            },
                {
                name: 'edit',
                icon: 'fa fa-pencil',
                title: __('Edit'),
                extend: 'data-toggle="tooltip" data-container="body" data-area=["100%","100%"]',
                classname: 'btn btn-xs btn-success btn-editone'
            }, {
                name: 'del2',
                icon: 'fa fa-trash',
                title: __('Del'),
                confirm:'确定删除吗？',
                url: 'knowbase/project_page_history/del',
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-danger btn-ajax',
                success:function (data){
                    table.bootstrapTable('refresh');
                }
            }];
            
            if (from =='project_page') {
                // 初始化表格
                table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.history_url,
                    pk: 'id',
                    sortName: 'id',
                    search: false,
                    fixedColumns: true,
                    fixedRightNumber: 1,
                    commonSearch: false,
                    detailView: false,
                    columns: [
                        [
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                            {field: 'remarks', title: __('Remarks'),operate:false},
                            {field: 'operate', title: __('Operate'), table: table, events: Controller.api.events.operate, formatter: Table.api.formatter.operate,buttons:buttons}
                        ]
                    ]
                });
            } else {
                // 初始化表格
                table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.history_url,
                    pk: 'id',
                    sortName: 'id',
                    search: false,
                    commonSearch: false,
                    detailView: false,
                    columns: [
                        [
                            {field: 'id', title: __('Id'),operate:false},
                            {field: 'knowbase_project_id', title: __('Knowbase_project_id'), searchList: function(column){
                                    return '<input id="c-knowbase_project_id"  data-source="knowbase/project/index" ' +
                                      'data-order-by="id" data-multiple="false" ' +
                                      'data-page-size="20"  '+
                                      'data-search-field="title" '+
                                      'data-field="title" ' +
                                      'data-pagination="true" '+
                                      'class="form-control selectpage" ' +
                                      'name="knowbase_project_id" type="text" value="">';
                                },formatter:function (value,row,index){
                                    return row.project?row.project.title:"--";
                                }},
                            {field: 'knowbase_project_page_id', title: __('Knowbase_project_page_id') ,searchList: function(column){
                                    return '<input id="c-knowbase_project_page_id"  data-source="knowbase/project_page/getList" ' +
                                      'data-order-by="id" data-multiple="false" ' +
                                      'data-page-size="20"  '+
                                      'data-search-field="title" '+
                                      'data-field="title" ' +
                                      'data-pagination="true" '+
                                      'class="form-control selectpage" ' +
                                      'name="knowbase_project_page_id" type="text" value="">';
                                },formatter:function (value,row,index){
                                    return row.project_page?row.project_page.title:"--";
                                }},
                            {field: 'admin_id', title: __('Admin_id'),searchList: function(column){
                                    return '<input id="c-admin_id"  data-source="auth/admin/index" ' +
                                      'data-order-by="id" data-multiple="false" ' +
                                      'data-page-size="20"  '+
                                      'data-search-field="username" '+
                                      'data-field="username" ' +
                                      'data-pagination="true" '+
                                      'class="form-control selectpage" ' +
                                      'name="admin_id" type="text" value="">';
                                },formatter:function (value,row,index){
                                    return row.admin?row.admin.username:"--";
                                }},
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                            {field: 'operate', title: __('Operate'), table: table, events: Controller.api.events.operate, formatter: Table.api.formatter.operate,buttons:buttons}
                        ]
                    ]
                });
            }
            


            // 为表格绑定事件
            Table.api.bindevent(table);
            top.bootstrapTable = table;
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            let diffJsonList = [];
            var diffJson = Diff2Html.parse(Diff.createPatch('',Config.content,Config.new_content,'修改前','修改后'));
            diffJsonList.push(diffJson[0]);
            var targetElement = document.getElementById('myDiffElement');
            var configuration = {
                drawFileList: false,
                fileListToggle: false,
                fileListStartVisible: false,
                fileContentToggle: false,
                matching: 'lines',
                outputFormat: 'side-by-side',
                synchronisedScroll: true,
                highlight: true,
                renderNothingWhenEmpty: false,
            };
            var ui = new Diff2HtmlUI.Diff2HtmlUI(targetElement, diffJsonList, configuration);
            ui.draw();
            ui.highlightCode();
            if (Fast.api.query('from')=='project_page') {
                $('.d2h-file-name').empty().append('<span>老版本</span><span>→</span><span>最新版</span>');
            } else {
                $('.d2h-file-name').empty().append('<span>修改前</span><span>→</span><span>修改后</span>');
            }
            $('#reduction').click(function (e) {
                e.preventDefault();
                var form = $("form[role=form]");
                var ids = $(this).attr('data-id');
                Layer.confirm(__('tips_reduction'), function (index) {
                    Layer.close(index);
                    Fast.api.ajax({
                        url: 'knowbase/project_page_history/reduction?ids=' + ids,
                        data: form.serialize()
                    }, function (data, ret) {
                        Fast.api.close();
                        parent.Toastr.success(data.msg);
                        if (parent.$(".btn-refresh").lengthj>0) {
                            parent.$(".btn-refresh").trigger("click");
                        } else {
                            parent.refresh = 1;
                        }
                    });
                });
            });

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"),function (data){
                    if (top.bootstrapTable && top.bootstrapTable.bootstrapTable) {
                        top.bootstrapTable.bootstrapTable('refresh', {});
                    }
                });
            },
            events:{
                operate:{
                    'click .btn-editone': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        var table = $(this).closest('table');
                        var options = table.bootstrapTable('getOptions');
                        var ids = row[options.pk];
                        row = $.extend({}, row ? row : {}, {ids: ids});
                        var url = options.extend.edit_url;
                        parent.parent.Fast.api.open(Table.api.replaceurl(url, row, table), $(this).data("original-title") || $(this).attr("title") || __('Edit'), $(this).data() || {});
                    },
                    'click .btn-compareone':function (e, value, row, index){
                      e.stopPropagation();
                      e.preventDefault();
                        var table = $(this).closest('table');
                        var options = table.bootstrapTable('getOptions');
                        var ids = row[options.pk];
                        row = $.extend({}, row ? row : {}, {ids: ids});
                        var url = 'knowbase/project_page_history/edit?ids='+row.id+'&from=project_page';
                        parent.parent.Fast.api.open(Table.api.replaceurl(url, row, table), $(this).data("original-title") || $(this).attr("title") || __('Edit'), $(this).data() || {});
                  }  
                }
            }
        }
    };
    return Controller;
});
